package com.baidu.sggc.core.common;


import com.alibaba.fastjson.JSON;

/**
 * @author yang
 */
public class R<T> {

  private int status = ResultCodeEnum.SUCCESS.code();
  private String message = "";
  private T result;

  public R() {
  }

  public R(int status, String message, T result) {
    this.status = status;
    this.message = message;
    this.result = result;
  }

  public static <T> R<T> ok() {
    return new R<T>().success(null);
  }

  public static <T> R<T> ok(T result) {
    return new R<T>().success(result);
  }

  public static <T> R<T> ok(String msg, T data) {
    return new R<T>().success(data).setMsg(msg);
  }

  public static <T> R<T> err() {
    return new R<T>().failed();
  }

  public static <T> R<T> err(String msg) {
    return new R<T>().failed().setMsg(msg);
  }


  public static <T> R<T> error(String msg, T data) {
    return new R<T>().failed(data).setMsg(msg);
  }

  public static <T> R<T> errWithData(T data) {
    return new R<T>().failed().setResult(data);
  }


  public T getResult() {
    return result;
  }

  public R<T> setResult(T result) {
    this.result = result;
    return this;
  }

  public R<T> success() {
    this.setStatus(200);
    this.setMsg("操作成功");
    return this;
  }



  public R<T> success(T result) {
    return new R<>(ResultCodeEnum.SUCCESS.code(), "操作成功", result);
  }

  public R<T> failed() {
    this.setStatus(-1);
    this.setMsg("操作失败");
    return this;
  }
  public R<T> failed(T result) {
    return new R<>(ResultCodeEnum.Fail.code(), "操作失败", result);
  }

  public int getCode() {
    return status;
  }

  public void setStatus(int status) {
    this.status = status;
  }

  public String getMsg() {
    return message;
  }

  public R<T> setMsg(String message) {
    this.message = message;
    return this;
  }

  @Override
  public String toString() {
    return JSON.toJSONString(this);
  }
}
